package com.ldj.hibernate;

import java.io.*;
import java.sql.*;
import java.util.*;
import javax.servlet.http.*;
import org.hibernate.*;
import org.hibernate.criterion.Projections;

import com.HibernateSessionFactory;


/**
 * Data access object (DAO) for domain model
 * @author MyEclipse Persistence Tools
 * 增加了翻页的功能
 */
public class BaseHibernateDAO implements IBaseHibernateDAO {
	
	HttpServletRequest request;

	HttpServletResponse response;

	Session session;

	//	定义List集合
	private List list;

	public int intCountic;

	public int PageSize;

	public int intPageCount;

	public int intPage;

	public String nowPage;

	public String HttpFile;



	//	取得网址是的参数
	String PageParameter;

	public BaseHibernateDAO(HttpServletRequest request, HttpServletResponse response) {

	    this.request = request;
	    this.response = response;
	}

	/*
	    *******得到Session**********
	    */
	public Session getSession() {
		return HibernateSessionFactory.getSession();
	}

//	添加数据
	public void add(Object obj) {
	}

//	修改数据
	public void mod(Object obj) {
	}

//	普通查询
	public List list() {
	    return null;
	}



	public List jlist(Object query, String countsql)
	{

	  
	    Query q=null;
	    Criteria cri=null;
	    List li=null;
	    

	    boolean bool=false;;
	  
	    //得到记录总数
	          if(query instanceof Query) {
	           q=(Query)query;
	           bool=true;
	     intCountic = getCountJsql(countsql);
	   
	    }
	        
	          else if(query instanceof Criteria) {
	          
	           cri=(Criteria)query;
	           li=cri.list();
	         
	       
	           if(li.size()==0)
	            intCountic=0;
	           else
	            intCountic=li.size();
	       
	    }
	          else
	          {
	         
	           System.out.println("出错提示：参数不正确");
	           return null;
	          }
	        
	     
	        
	    try
	    {
	    //每页记录数 
	        if (PageSize == 0)
	     PageSize = 20;

	    //获得url，如 /user/china.jsp
	    HttpFile = request.getRequestURI();

	    //获得当前页数
	    nowPage = request.getParameter("pages");

	    //取得网址是的参数
	    PageParameter = this.urlPath(request);

	    //如果没有pages参数，则让页数为1
	    if (nowPage == null) {
	     intPage = 1;
	    }

	    else {
	     intPage = Integer.parseInt(nowPage);
	     if (intPage < 1) {
	      intPage = 1;
	     }
	    }

	  

	    //得到分页总数
	    intPageCount = ((intCountic + PageSize) - 1) / PageSize;

	    if (intPage > intPageCount) {
	     intPage = intPageCount;
	    }
	    
//	    得到list集合
	   
	     if(bool)
	     list = q.setFirstResult((intPage - 1) * PageSize).setMaxResults(PageSize).list();    
	     else
	        list =cri.setFirstResult((intPage - 1) * PageSize).setMaxResults(PageSize).list(); 
	   

	   
	    }
	    catch(Exception ex)
	    {
	     ex.printStackTrace();
	    }
	    finally
	    {
	     
	    }
	  
	    //将分页和页脚传到request中
	          request.setAttribute("list", list);
	          request.setAttribute("foot", PageFooter());
	          request.setAttribute("totalNum", intCountic);
	          request.setAttribute("pageNum", (intPage - 1) * PageSize);
	    return list;
	}






	public List jlist(Query query)
	{
	  
	      String[] str = query.getQueryString().split("from");  
	      String countsql ="select count(*) ";  
	      for(int i = 1; i < str.length; i ++){
	    	  countsql += " from " + str[i].trim();
	      }
	      return jlist(query,countsql);  
	  
	}

	public List jlist(Criteria query)
	{
	  
	    return jlist(query,"");
	   
	  
	}





//	汇总语句,得到记录总数
	public int getCountJsql(String countsql) {
	    Query q = getSession().createQuery(countsql);
	    List cc = q.list();
	    Integer a = (Integer) cc.get(0);
	    return a.intValue();
	}

//	页脚显示
	/**
	    * 显示分页内容
	    * @return
	    */
	public String PageFooter() {


	    if (list.size() <= 0) {
	         return "<span style=\"color:#FF3300;font-size:14px;\">对不起，没有查询到数据！</span>";
	          }
	  
	    String script = "<script type=\"text/javascript\"> \n";
	    script += "function goPage(page){ \n";
	    script += "document.pageForm.pages.value=page; \n";
	  //  script += "document.getElementById(\"p\").innerHTML=page; \n";
	  //  script +="alert(document.pageForm.pages.value);";
	    
	    script += "document.pageForm.submit(); \n";
	    script += "} \n";
	    script += "function getPage(){ \n";
	    script += "var p = document.getElementById(\"page\").value; \n";
	    script += "if(p != null && p != \"\"){ \n";
	    script += "goPage(p) \n";
	    script += "}else{ \n";
	    script += "alert(\"请输入合法参数！\"); \n";
	    script += "return; \n";
	    script += "} \n";
	    script += "} \n";
	    script += "</script> \n";
	    script += "<input type=\"hidden\" name=\"pages\" value=\"\"/>";
	    String str = "";
	    int prev = intPage - 1;
	    int next = intPage + 1;
	    str = str + " 共 " + intCountic + " 条 第 " + intPage + " / " + intPageCount + " 页";
	    if (intPage > 1) {
	     str = str + " <input name=\"button\" type=\"button\" class=\"pagefirst\" onclick=\"goPage('1')\"/> <input name=\"button\" type=\"button\" class=\"pageback\" onclick=\"goPage('" + prev + "')\"/> ";
	    } else {
	     str = str + " <input name=\"button\" type=\"button\" class=\"pagefirst\" disabled/> <input name=\"button\" type=\"button\" class=\"pageback\" disabled/> ";
	    }
	    if (intPage < intPageCount) {
	     str = str + " <input name=\"button\" type=\"button\" class=\"pagenext\" onclick=\"goPage('" + next + "')\"/> <input name=\"button\" type=\"button\" class=\"pagelast\" onclick=\"goPage('" + intPageCount + "')\"/> ";
	    } else {
	     str = str + " <input name=\"button\" type=\"button\" class=\"pagenext\" disabled/> <input name=\"button\" type=\"button\" class=\"pagelast\" disabled/> ";
	    }
	    str = str
	      + " 跳转到第<input class=\"pagemub\" id=\"page\" name=\"page\" type=\"text\" value=\"" + intPage + "\" size=\"3\" maxlength=\"5\" onkeyup=\"javascript:value=value.replace(/[^\\d]/g,'')\" /><input name=\"button\" type=\"button\" class=\"pagego\" onclick=\"getPage()\" /> ";
	    return script + str;
	}

	/**
	    * 对有参数的网址进行改造。。
	    * 如 index.jsp?id=23&class=23
	    */

	public String urlPath(HttpServletRequest request) {
	    String path = "";
	    String pagepath = "pages=";
	    String url = request.getQueryString();

	    //如果无参数
	    if (url == null || url.equals("")) {
	     return pagepath;
	    }

	    List lista = new ArrayList();
	    StringTokenizer ss = new StringTokenizer(url, "&");

	    while (ss.hasMoreTokens()) {
	     String s = ss.nextToken();
	     if (s.indexOf("pages") == -1)
	      lista.add(s);
	    }

	    for (int i = 0; i < lista.size(); i++) {
	     String param = "";
	     try {
	      param = new String(lista.get(i).toString().getBytes(
	        "iso-8859-1"), "gb2312");
	     } catch (UnsupportedEncodingException e) {

	      e.printStackTrace();
	     }
	     path += param + "&";
	    }

	    return path + pagepath;

	}

	public int getIntCountic() {
	    return intCountic;
	}

	public void setIntCountic(int intCountic) {
	    this.intCountic = intCountic;
	}

	public int getIntPage() {
	    return intPage;
	}

	public void setIntPage(int intPage) {
	    this.intPage = intPage;
	}

	public int getIntPageCount() {
	    return intPageCount;
	}

	public void setIntPageCount(int intPageCount) {
	    this.intPageCount = intPageCount;
	}

	public String getNowPage() {
	    return nowPage;
	}

	public void setNowPage(String nowPage) {
	    this.nowPage = nowPage;
	}

	public int getPageSize() {
	    return PageSize;
	}

	public void setPageSize(int pageSize) {
	    PageSize = pageSize;
	}


	
}